package cn.gzmli.dtt.common.filters;
import cn.gzmli.dtt.sbzyc.config.FilePropertiesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author wonderful 20190630 1616
 * 请求过滤类，用作统一的访问资源控制、登陆和主页页面引导、初步的权限控制。
 */
//@Order规定多个Filter的执行顺序,按照从小到大执行()中的值
@Order(1)
//@WebFilter过滤对应的请求路径
@WebFilter(urlPatterns = {"/*"},filterName = "mainFilter")
public class MainFilter implements Filter{

    @Autowired
    private FilePropertiesConfig filePropertiesConfig;


    /** 过滤规则  **/

    private static Set<String> suffixSet = new HashSet<>();

    private static Set<String> urlSet = new HashSet<>();

    static{
        /* 放行静态资源 */
        suffixSet.add("js");
        suffixSet.add("css");
        suffixSet.add("jpeg");
        suffixSet.add("jpg");
        suffixSet.add("png");
        suffixSet.add("gif");
        suffixSet.add("ico");
        suffixSet.add("pdf");

        /* 放行url路径 */
        //放行登录
        urlSet.add("/system/login");
        //放行springbootadmin心跳检测
        urlSet.add("/actuator/health");
        //放行webSocket长连接接口
        urlSet.add("/msgwebsocket");
        //放行springbootadmin监控请求
        urlSet.add("/actuator");
        //放行文件下载请求
        urlSet.add("/fileUpload/downloadFile");

        //放心页面访问前缀
        urlSet.add("/dtt/main");

    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        request.getSession().setAttribute("basePath",basePath);
        request.getSession().setAttribute("fileServerPath",filePropertiesConfig.getFilePath());
        String sessionId=session.getId();
        if(!StringUtils.isEmpty(request.getParameter("flowID"))){
            //在workFlowView.html 中使用，var flowID="[[${session.flowID}]]";
            String flowID = request.getParameter("flowID");
            request.getSession().setAttribute("flowID",flowID);
        }
        String msg = "" ;
        String fullPath = request.getRequestURL().toString();
        request.setCharacterEncoding("UTF-8");
        String sourceName = fullPath.substring(fullPath.lastIndexOf("/"));
        String templateUrl=request.getParameter("url");
        if(sourceName.lastIndexOf(".")!=-1){
            String suffix=sourceName.substring(sourceName.lastIndexOf(".")+1);
            for (String str:suffixSet){
                if(str.equalsIgnoreCase(suffix)){
                    filterChain.doFilter(request,response);
                    return;
                }
            }
        }
        //放行layui静态资源
        if(fullPath.indexOf("layui2") != -1){
            filterChain.doFilter(request,response);
            return;
        }

        String sourceUrl=fullPath.substring(fullPath.indexOf("//")+2);
        sourceUrl=sourceUrl.substring(sourceUrl.indexOf("/"));

        // 正则表达式过滤规则
        for(String url:urlSet){
            if(Pattern.matches(url, sourceUrl)){
                filterChain.doFilter(request, response);
                return;
            }
        }

        if( templateUrl!=null&&templateUrl.indexOf("login/login") != -1){
            filterChain.doFilter(request,response);
            return;
        }

        if(session.getAttribute("User")==null&&sourceName.equals("/")){
            request.getRequestDispatcher("/dtt/main?url=imp/system/login/login").forward(request,response);
        } else if (session.getAttribute("User") == null&&!sourceName.equals("/")) {
            String tipMsg = "您还未登录或登陆超时，请先登录！";
            msg = "<script language='javascript'>alert('"+tipMsg+"');window.top.location='"
                    + basePath + "/dtt/main?url=imp/system/login/login';</script>";

            //设置缓冲区中使用的编码为UTF-8
            response.setCharacterEncoding("UTF-8");
            //设置浏览器接受内容时所使用的编码方式
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(msg);
            response.getWriter().flush();
            response.getWriter().close();
        }else if(sourceName.equals("/")){
            request.getRequestDispatcher("/dtt/main?url=imp/main").forward(request,response);
        }else{
            filterChain.doFilter(request,response);
        }

    }

    @Override
    public void destroy() {

    }


}
